package com.zhongxi.guoyuan.view.seller;

import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.WithDrawAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.WithDrawResult;
import com.zhongxi.guoyuan.url.Url;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SellerCoinExchangeActivity extends BaseActivity implements View.OnClickListener, PullToRefreshBase.OnRefreshListener2<ListView> {

    private EditText etInput;
    private PullToRefreshListView lvList;
    private TextView tvExchange;
    private String type;
    private List<WithDrawResult.WithDrawData> list = new ArrayList();
    private WithDrawAdapter adapter;
    private WithDrawResult result;
    private TextView tvAllCoin;
    private TextView tvRestCoin;
    private Map<String, String> map = new HashMap<>();

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_seller_exchange);
        initTitle();
        tvTitle.setText("申请兑换");
        etInput = (EditText) findViewById(R.id.etInput);
        lvList = (PullToRefreshListView) findViewById(R.id.lvList);
        lvList.setMode(PullToRefreshBase.Mode.BOTH);
        tvExchange = (TextView) findViewById(R.id.tvExchange);
        tvAllCoin = (TextView) findViewById(R.id.tvAllCoin);
        tvRestCoin = (TextView) findViewById(R.id.tvRestCoin);
    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new WithDrawAdapter(this, list);
        lvList.setAdapter(adapter);
        getData();
    }

    /**
     * 获取兑换记录数据
     */
    private void getData() {
        type = "data";
        String str = "&page="+pageNum;
        getServer(Url.COIN_DRAW_LIST, null, str, true, null, "get");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        tvExchange.setOnClickListener(this);
        lvList.setOnRefreshListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvExchange:
                String amount = etInput.getText().toString().trim();
                if(TextUtils.isEmpty(amount)){
                    showShortToast("请输入提现的银币数！");
                }else if(Integer.parseInt(amount)>Integer.parseInt(result.getLastEarnings())){
                    showShortToast("提现金额超限，请重新输入金额");
                }else {
                    dialog(amount);
                }
                etInput.setText("");
                break;
        }
    }

    /**
     * 确认兑换dialog
     * @param amount
     */
    private void dialog(final String amount) {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_exchange, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(layout);
        TextView tvCoin = (TextView) layout.findViewById(R.id.tvCoin);
        TextView tvCancle = (TextView) layout.findViewById(R.id.tvCancle);
        TextView tvSure = (TextView) layout.findViewById(R.id.tvSure);
        tvCoin.setText(amount+"银币");
        /**
         * 取消
         */
        tvCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               dialog.dismiss();
            }
        });
        /**
         * 确定
         */
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toApply(amount);
                dialog.dismiss();
            }
        });
    }

    /**
     * 申请兑换
     * @param amount
     */
    private void toApply(String amount) {
        if(TextUtils.isEmpty(amount)){
            showShortToast("请输入提现的银币数！");
        }else{
            type = "apply";
            map.clear();
            map.put("amount", amount);
            getServer(Url.COIN_DRAW, map, "", true, null, "post");
        }
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            if("data".equals(type)){
                result = gson.fromJson(response, WithDrawResult.class);
                if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                if(pageNum == 1){
                    list.clear();
                }
                if(null!=result.getList()&&result.getList().size()>0){
                    list.addAll(result.getList());
                }
                if(null!=result.getEarningsNum()&&!"".equals(result.getEarningsNum())){
                    tvAllCoin.setText(result.getEarningsNum()+"银币");
                }
                if(null!=result.getLastEarnings()&&!"".equals(result.getLastEarnings())){
                    tvRestCoin.setText(result.getLastEarnings()+"银币");
                }
                lvList.onRefreshComplete();
                adapter.notifyDataSetChanged();
            }else if("apply".equals(type)){
                BaseResponse result = gson.fromJson(response, BaseResponse.class);
                if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }
                showShortToast("申请成功");
                pageNum = 1;
                getData();
                showResult(1);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 申请兑换成功
     * @param i
     */
    private void showResult(int i) {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_exchange_result, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
        dialog.getWindow().setContentView(layout);
        TextView tvSurePay = (TextView) layout.findViewById(R.id.tvSure);
        TextView tv = (TextView) layout.findViewById(R.id.tv);
        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tvSurePay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        if (i == 0) {
            tv.setText("申请兑换失败！");
        }else if(i == 1){
            tv.setText("申请兑换成功！");
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try{
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            if(9002==result.getCode()){
                showShortToast("商家未登录");
                finish();
            }else if(9003==result.getCode()){
                showShortToast("店铺已下架");
                finish();
            }else if(9004==result.getCode()){
//                showShortToast("");
            }else if(9005==result.getCode()){
                showShortToast("非法提现");
            }else if(9006==result.getCode()){
                showShortToast("提现金额超限，请重新输入提现金额");
            }
            if("apply".equals(type)){
                showResult(0);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum=1;
        getData();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum++;
        getData();
    }
}
